package o2o.web.actions.order;

import com.jinyou.utils.common.AjaxResult;
import com.jinyou.utils.common.JYListSort;
import com.jinyou.utils.common.ObjectUtils;
import com.jinyou.utils.common.ValidateUtil;
import io.swagger.annotations.*;
import o2o.cache.order.*;
import o2o.cache.postman.CityPostmanMemory;
import o2o.cache.shop.ShopMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.config.dao.DataDaoSql;
import o2o.config.dao.MongoDaoImpl;
import o2o.config.dao.utils.DaoUtils;
import o2o.config.dao.utils.Expression;
import o2o.config.dao.utils.QueryCondition;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.common.UserType;
import o2o.dao.PO.order.*;
import o2o.postman.model.CityPostman;
import o2o.dao.PO.release.ReleaseInformationMongo;
import o2o.company.model.ShopInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.order.*;
import o2o.dao.VO.postman.CityPostmanVO;
import o2o.service.delivery.DeliveryOrderSyncService;
import o2o.service.delivery.to.DeliveryOrderStateTO;
import o2o.service.order.shop.ShopOrderService;
import o2o.system.data.PROMPTS;
import o2o.system.data.SYS_SETTINGS;
import o2o.utils.MultilingualResult;
import o2o.web.actions.order.user.UserOrderMan;
import o2o.web.actions.postman.PostmanMan;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static o2o.web.actions.order.OrderMan.getOrderDetail;

//订单
@Api(tags = "订单管理")
@Controller
public class OrderAction {

    // 哒哒订单 状态 回调
    @RequestMapping("/delivery/order/notify")
    @ResponseBody
    public String delivery_order_callback(String json) {
        System.out.println("回调了数据--->" + json);
        if (ValidateUtil.isNull(json)) {
            return AjaxResult.errorResult("信息不能为空");
        }
        DeliveryOrderStateTO orderStateTO = DeliveryOrderSyncService.getInstance().getDeliveryState(json);
        if (orderStateTO == null) {
            return AjaxResult.errorResult("信息不能为空");
        }
        try {
            ShopOrderService.getInstance().dealDeliveryOrderState(orderStateTO, false);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }
        System.out.println("回调的数据解析成功-->");
        return AjaxResult.successResult();
    }

    //获取某一订单详情
    @RequestMapping(method = RequestMethod.POST, value = "/user/order/info")
    @ResponseBody
    public String user_order_info(String token, String orderNo, String lang) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (ValidateUtil.isNull(orderNo)) {
            return AjaxResult.errorResult("订单编号不能为空");
        }
        // 聚合订单 ？
        if (OrderMan.isMultipleParentOrder(orderNo)) {
            //订单信息
            OrderInfoVO infoVO = OrderMan.getMultipleParentOrderDetail(orderNo, user);
            if (null == infoVO) {
                return AjaxResult.errorResult("当前订单不存在请查证");
            }
            // 将数据整合上
            if (ValidateUtil.isAbsList(infoVO.getOrderInfoList())) {
                List<OrderGoodsVO> list = new ArrayList<>();
                for (OrderInfoVO orderInfoVO : infoVO.getOrderInfoList()) {
                    if (ValidateUtil.isAbsList(orderInfoVO.getGoods())) {
                        list.addAll(orderInfoVO.getGoods());
                    }
                }
                infoVO.setGoods(list);
            }
            return AjaxResult.successResult(infoVO);
        }
        // 非聚合订单

        //订单信息
        OrderInfoVO infoVO = getOrderDetail(orderNo);
        if (null == infoVO) {
            return MultilingualResult.errorResultV2(PROMPTS.ORDER_NOT_EXIST, lang);
        }
        // add by yangtk 返回信息添加店铺的环信账号
        if (ValidateUtil.isID(infoVO.getShopId())) {
            ShopInfo shopInfo = ShopMemory.getInstance().getShopById(infoVO.getShopId());
            if (null != shopInfo) {
                UserInfo shopUser = UserInfoMemory.getInstance().getUserInfo(shopInfo.getOwnUsername());
                if (null != shopUser && shopUser.getHxAccount() != null && !"".equals(shopUser.getHxAccount())) {
                    infoVO.setShopHxAccount(shopUser.getHxAccount());
                }
            }
        }

        //跑腿订单详情
        if (null != infoVO.getOrderType()) {
            OtherOrderInfoVO otherOrderInfoVO = getPaotuiInfo(infoVO.getOrderType(), orderNo);
            infoVO.setOtherOrderInfo(otherOrderInfoVO);
        }

        return AjaxResult.successResult(infoVO);
    }

    //获取某一订单详情
    @ApiOperation("获取某一订单详情")
    @RequestMapping(method = RequestMethod.POST, value = "/order/info")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "用户登录凭证",dataType = "string",required = true),
            @ApiImplicitParam(name = "orderNo",value = "订单号",required = true)
    })
    public AjaxResult<OrderInfoVO> order_info(String token, String orderNo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.<OrderInfoVO>builder()
                    .status(0)
                    .type("noLogin")
                    .error("当前帐号失效，请重新登录")
                    .build();
        }

        if (ValidateUtil.isNull(orderNo)) {
            return AjaxResult.<OrderInfoVO>builder()
                    .status(0)
                    .type("comError")
                    .error("订单编号不能为空")
                    .build();
        }
        // 聚合订单 ？
        if (OrderMan.isMultipleParentOrder(orderNo)) {
            //订单信息
            OrderInfoVO infoVO = OrderMan.getMultipleParentOrderDetail(orderNo, user);
            if (null == infoVO) {
                return AjaxResult.<OrderInfoVO>builder()
                        .status(0)
                        .type("comError")
                        .error("当前订单不存在请查证")
                        .build();
            }
            if (ValidateUtil.isAbsList(infoVO.getOrderInfoList())) {
                List<OrderGoodsVO> goods = new ArrayList<>();
                for (OrderInfoVO vo : infoVO.getOrderInfoList()) {

                    if (vo == null) {
                        continue;
                    }

                    if (ValidateUtil.isAbsList(vo.getGoods())) {
                        goods.addAll(vo.getGoods());
                    }
                }
                infoVO.setGoods(goods);
            }
            return AjaxResult.<OrderInfoVO>builder()
                    .status(1)
                    .info(infoVO)
                    .build();
        }
        // 非聚合订单

        OrderInfoVO infoVO = getOrderDetail(orderNo, user.getUserType());
        if (null == infoVO) {
            return AjaxResult.<OrderInfoVO>builder()
                    .status(0)
                    .type("comError")
                    .error("当前订单不存在请查证")
                    .build();
        }
        // 是否转单记录 有的话  直接查询返回
        if (infoVO.getIsChangedAddress() == 1) {
            infoVO.setOrderChangeAddressRecordList(OrderMan.listOrderChangeAddressRecordByOrderNo(orderNo));
        }

//        //如果是用户的显示自取或到店验证码
//        if (0 == UserType.USER - user.getUserType() && 0 == 1 - infoVO.getIsZiQu()) {
//
//        } else {
//            infoVO.setVerifyCode(null);
//        }

        String verifyCode = null;
        switch (user.getUserType()) {
            case UserType.USER: {
                //如果是用户的显示自取或到店验证码
                if (0 == 1 - infoVO.getIsZiQu()) {
                    verifyCode = infoVO.getVerifyCode();
                }
            }
            break;
//            case UserType.SHOP_OWNER: {
//                OrderPayInfo orderPayInfo = OrderPayMemory.getInstance().get(orderNo);
//                if (null != orderPayInfo) {
//                    infoVO.setShopMoney(orderPayInfo.getShopMoney());
//                }
//            }
//            break;
        }
        infoVO.setVerifyCode(verifyCode);

        //获取收益
        OrderPayInfo orderPay = OrderPayMemory.getInstance().get(orderNo);
        if (null != orderPay) {
            OrderPayInfoVO payInfoVO = new OrderPayInfoVO();
            try {
                ObjectUtils.copyPropertiesExclude(orderPay, payInfoVO, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
            infoVO.setShopMoney(orderPay.getShopMoney());
            infoVO.setOrderPay(payInfoVO);
        }

        if (ValidateUtil.isNotNull(infoVO.getPostManUsername())) {
            CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(infoVO.getPostManUsername());
            if (null != cityPostman) {
                CityPostmanVO postmanVO = PostmanMan.getOne(cityPostman);
                infoVO.setPostmanInfo(postmanVO);
            }
        }
        // 获取订单额外信息
        OrderInfoExtra infoExtra = OrderInfoExtraMemory.getInstance().getOrderInfoExtraByOrderNo(orderNo);
        infoVO.setOrderInfoExtra(infoExtra);

        //跑腿订单详情
        if (null != infoVO.getOrderType()) {
            OtherOrderInfoVO otherOrderInfoVO = getPaotuiInfo(infoVO.getOrderType(), orderNo);
            infoVO.setOtherOrderInfo(otherOrderInfoVO);
        }

        return AjaxResult.<OrderInfoVO>builder()
                .status(1)
                .info(infoVO)
                .build();
    }

    //获取某一订单详情
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/info")
    @ResponseBody
    public String admin_order_info(String token, String orderNo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        Integer userType = user.getUserType();
        if (ValidateUtil.isNull(orderNo)) {
            return AjaxResult.errorResult("订单编号不能为空");
        }
        // 聚合订单 ？
        if (OrderMan.isMultipleParentOrder(orderNo)) {
            //订单信息
            OrderInfoVO infoVO = OrderMan.getMultipleParentOrderDetail(orderNo, user);
            if (null == infoVO) {
                return AjaxResult.errorResult("当前订单不存在请查证");
            }
            if (ValidateUtil.isAbsList(infoVO.getOrderInfoList())) {
                List<OrderGoodsVO> goods = new ArrayList<>();
                for (OrderInfoVO vo : infoVO.getOrderInfoList()) {

                    if (vo == null) {
                        continue;
                    }

                    if (ValidateUtil.isAbsList(vo.getGoods())) {
                        goods.addAll(vo.getGoods());
                    }
                }
                infoVO.setGoods(goods);
            }
            return AjaxResult.successResult(infoVO);
        }
        // 非聚合订单
        OrderInfoVO infoVO = getOrderDetail(orderNo, user.getUserType());
        if (null == infoVO) {
            return AjaxResult.errorResult("当前订单不存在请查证");
        }

        //获取收益
        OrderPayInfo orderPay = OrderPayMemory.getInstance().get(orderNo);
        if (null != orderPay) {
            if (null != SYS_SETTINGS.USE_BAK_ORDER && 0 == 1 - SYS_SETTINGS.USE_BAK_ORDER) {
                if (null != userType && (0 == UserType.ADMIN - userType || 0 == UserType.SUPER_ADMIN - userType || 0 == UserType.COMPANY - userType)) {
                    // 获取data表的数据
                    QueryCondition query = QueryCondition.getInstance();
                    Expression expressions = Expression.getInstance().addChild("delFlag", 0).addChild("orderNo", orderNo);
                    query.addCondition(expressions);
                    String sql = DaoUtils.getSql(PojoTables.D_ORDER_PAY, query);
                    try {
                        orderPay = (OrderPayInfo) DataDaoSql.getInstance().getObject(OrderPayInfo.class, sql);
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
            if (null != orderPay) {
                OrderPayInfoVO payInfoVO = new OrderPayInfoVO();
                try {
                    ObjectUtils.copyPropertiesExclude(orderPay, payInfoVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                infoVO.setShopMoney(orderPay.getShopMoney());
                infoVO.setOrderPay(payInfoVO);
            }
        }

        if (ValidateUtil.isNotNull(infoVO.getPostManUsername())) {
            CityPostman cityPostman = CityPostmanMemory.getInstance().getPostman(infoVO.getPostManUsername());
            if (null != cityPostman) {
                CityPostmanVO postmanVO = PostmanMan.getOne(cityPostman);
                infoVO.setPostmanInfo(postmanVO);
            }
        }
        // 获取订单额外信息
        OrderInfoExtra infoExtra = OrderInfoExtraMemory.getInstance().getOrderInfoExtraByOrderNo(orderNo);
        infoVO.setOrderInfoExtra(infoExtra);

        //跑腿订单详情
        if (null != infoVO.getOrderType()) {
            OtherOrderInfoVO otherOrderInfoVO = getPaotuiInfo(infoVO.getOrderType(), orderNo);
            infoVO.setOtherOrderInfo(otherOrderInfoVO);
        }

        return AjaxResult.successResult(infoVO);
    }


    //获取某一订单的订单状态
    @RequestMapping(method = RequestMethod.POST, value = "/order/status")
    @ResponseBody
    public String order_status(String token, String orderNo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        List<OrderStatus> list = OrderStatusMemory.getInstance().list(orderNo);
        if (null != list && list.size() > 0) {
            List<OrderStatusVO> voList = new ArrayList<OrderStatusVO>();
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                OrderStatusVO orderStatusVO = new OrderStatusVO();
                try {
                    ObjectUtils.copyPropertiesExclude(list.get(i), orderStatusVO, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (0 == orderStatusVO.getOrderStatus() - ORDER_STATUS.PEISONG
                        || 0 == orderStatusVO.getOrderStatus() - ORDER_STATUS.POSTMAN_ZHIDING
                        || 0 == orderStatusVO.getOrderStatus() - ORDER_STATUS.POSTMAN_SURE
                        || 0 == orderStatusVO.getOrderStatus() - ORDER_STATUS.POSTMAN_DAODIAN
                        || 0 == orderStatusVO.getOrderStatus() - ORDER_STATUS.POSTMAN_FINISH
                        || 0 == orderStatusVO.getOrderStatus() - ORDER_STATUS.POSTMAN_CANT_FINISH
                        || 0 == orderStatusVO.getOrderStatus() - ORDER_STATUS.SHOP_PUSH_GOODS
                        || 0 == orderStatusVO.getOrderStatus() - ORDER_STATUS.SHOP_READY
                        || 0 == orderStatusVO.getOrderStatus() - ORDER_STATUS.POSTMAN_PULL_GOODS) {
                    //获取配送员电话
                    OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
                    if (null != orderInfo) {
                        if (ValidateUtil.isNotNull(orderInfo.getPostmanPhone())) {
                            orderStatusVO.setUserPhone(orderInfo.getPostmanPhone());
                        } else {
                            orderStatusVO.setUserPhone(orderInfo.getPostManUsername());
                        }
                    }
                }

//                //用户信息
//                UserInfo info = UserInfoMemory.getInstance().getUserInfo(orderStatusVO.getCreateUser());
//                orderStatusVO.setUserPhone(info.getTelPhone());

                voList.add(orderStatusVO);
            }
            JYListSort.sort(voList, "createTime");

            return AjaxResult.successResult(voList.size(), voList);
        }

        return AjaxResult.successResult();
    }

    // 获取聚合订单情况
    @RequestMapping(method = RequestMethod.POST, value = "/user/multiple/order/info")
    @ResponseBody
    public String user_multiple_order_info(String token, String orderNo) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //订单信息
        OrderInfoVO infoVO = OrderMan.getMultipleParentOrderDetail(orderNo, user);
        if (null == infoVO) {
            return AjaxResult.errorResult("当前订单不存在请查证");
        }
        return AjaxResult.successResult(infoVO);
    }


    //获取跑腿订单详情
    private OtherOrderInfoVO getPaotuiInfo(Integer orderType, String orderNo) {
        //跑腿订单详情
        if (null != orderType && (
                0 == ORDER_TYPE.PAO_TUI - orderType
                        || 0 == ORDER_TYPE.DAI_GOU - orderType
                        || 0 == ORDER_TYPE.BANG_BAN - orderType
                        || 0 == ORDER_TYPE.HUO_YUN - orderType)
        ) {
            //获取订单详情
            OtherOrderInfo info = OtherOrderMemory.getInstance().getByOrderNo(orderNo);
            if (null != info) {
                OtherOrderInfoVO vo = new OtherOrderInfoVO();
                try {
                    ObjectUtils.copyPropertiesExclude(info, vo);
                } catch (Exception e) {
                    e.printStackTrace();
                    vo = null;
                }
                return vo;
            }
        }
        return null;
    }

    //----------------
    // 自动派单失败原因
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/dispatch/error/info")
    @ResponseBody
    public String order_error_info(String token, String orderNo) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
//            return AjaxResult.errorLogoutResult();
        }
        Map<String, Object> query = new HashMap<>();
        query.put("orderNo", orderNo);
        List<HashMap<String, Object>> list = MongoDaoImpl.getInstance().find(ReleaseInformationMongo.onlineLogMongoDB, PojoTables.MG_DISPATCH_LOG, query, 1);
        if (ValidateUtil.isAbsList(list)) {
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                list.get(i).remove("_id");
            }
        }

        return AjaxResult.successResult(list);
    }

    // 处理用户是否有订单
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/user/has")
    @ResponseBody
    public String user_order_info(String token, String username) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        UserOrderMan.doUserOrder(username, user.getUsername());
        return AjaxResult.successResult();
    }

    // 获取订单状态列表
    @RequestMapping(method = RequestMethod.POST, value = "/admin/order/status/name/list")
    @ResponseBody
    public String admin_order_status_list(String token) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        List<OrderStatusName> statusNameList = OrderStatusNameMemory.getInstance().listAll(null);
        if (ValidateUtil.isAbsList(statusNameList)) {
            return AjaxResult.successResult(statusNameList, statusNameList.size());
        }
        return AjaxResult.successResult(0, null);
    }


}
